/**
 * Copyright (c) 时间, Tal.Ben 袁东昊 (ydonghao2@gmail.com).
 *
 * 版权
 */
package com.talben.soudian.adapter;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.Header;
import org.json.JSONObject;
import org.kymjs.kjframe.KJDB;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;

import com.koushikdutta.ion.Ion;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.talben.soudian.AppConfig;
import com.talben.soudian.AppContext;
import com.talben.soudian.R;
import com.talben.soudian.TDevice;
import com.talben.soudian.api.SouDianAPI;
import com.talben.soudian.api.UrlConnect;
import com.talben.soudian.apkinstaller.ApkTaskManager;
import com.talben.soudian.bean.ApkDetail;
import com.talben.soudian.service.ScoreService;
import com.talben.soudian.util.FileUtil;
import com.talben.soudian.util.StringUtils;


/**
 * @Title: ApkAdapter.java
 * @Package com.talben.soudian
 * @Description: TODO(添加描述)
 * @author Tal.Ben
 * @date 2015年5月31日 下午3:29:06
 * @version v1.0
 */
public class ApkAdapter extends ListBaseAdapter<ApkDetail> {

	private Context mContext;
	
	public ApkAdapter() {
		super();
	}
	
	public ApkAdapter(Context mContext){
		this.mContext = mContext;
	}

	@SuppressLint("InflateParams")
    @Override
    protected View getRealView(int position, View convertView, ViewGroup parent) {
        ViewHolder vh = null;
        if (convertView == null || convertView.getTag() == null) {
            convertView = getLayoutInflater(parent.getContext()).inflate(
                    R.layout.list_cell_apk, null);
            vh = new ViewHolder(convertView);
            convertView.setTag(vh);
        } else {
            vh = (ViewHolder) convertView.getTag();
        }

        final ApkDetail apkDetail = mDatas.get(position);
        
        Ion.with(vh.mApkLogo)
           .load(UrlConnect.HOST+apkDetail.getApkIcon());
        vh.mTvApkName.setText(apkDetail.getName());
        String description = apkDetail.getDescription();
        vh.mTvApkInfo.setVisibility(View.GONE);
        if (description != null && !StringUtils.isEmpty(description)) {
            vh.mTvApkInfo.setVisibility(View.VISIBLE);
            vh.mTvApkInfo.setText(Html.fromHtml(description.trim()));
        }
        vh.mTvApkDownloadTimes.setText(apkDetail.getDownloadTimes());
        vh.mTvApkScore.setText(apkDetail.getScore());
        vh.mTvApkCoin.setText(apkDetail.getCoin());
        vh.mBtnDownload.setText(apkDetail.getBtnStatus());
        final Button button = vh.mBtnDownload;
        vh.mBtnDownload.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (TDevice.isNetworkReady(mContext)) {
					if (apkDetail.getBtnStatus().equals("打开")) {
						TDevice.openFreeApp(mContext, apkDetail.getPackageName());
//						if (AppContext.getInstance().getLoginUser().getuPhone() != null) {
//							Intent intent = new Intent(mContext, ScoreService.class);
//							intent.putExtra("appname", apkDetail.getName());
//							intent.putExtra("id", apkDetail.getId());
//							intent.putExtra("pkgName", apkDetail.getPackageName());
//							KJDB db = KJDB.create(mContext);
//							List<ApkDetail> apkList = db.findAllByWhere(ApkDetail.class, "packageName="+apkDetail.getPackageName());
							//context.startService(intent);
//							for (ApkDetail apkInstalled : apkList) {
//								int opentimes = apkInstalled.getOpentimes();
//								int opencount = apkInstalled.getOpencount();
//								if ((++opencount) % opentimes == 0) {
//									apkInstalled.setOpencount(opencount);
//									db.update(apkInstalled);
//									SouDianAPI.getScore(AppContext.getInstance().getLoginUser().getuPhone(), apkDetail.getServerId() , mHandler);
//								}
//							}
//						}
					} else if (apkDetail.getBtnStatus().equals("安装")) {
						TDevice.installAPK(mContext, new File(AppConfig.DEFAULT_SAVE_FILE_PATH + apkDetail.getName()+ ".apk"));
						KJDB db = KJDB.create(mContext);
						List<ApkDetail> apkList = db.findAllByWhere(ApkDetail.class, "packageName='"+apkDetail.getPackageName()+"'");
						for (ApkDetail apkInstalled : apkList) {
							apkInstalled.setBtnStatus("打开");
							db.update(apkInstalled);
						}
					} else {
						ApkTaskManager apkTask = new ApkTaskManager(mContext, apkDetail);
						File file = new File(AppConfig.DEFAULT_SAVE_FILE_PATH);
						if (!file.exists()) {
							file.mkdirs();
						}
						apkTask.downloadFile();
						button.setText("打开");
					}
				} else {
					AppContext.showToast(R.string.tip_no_internet);
				}
			}
		});
        return convertView;
    }

    static class ViewHolder {
        @InjectView(R.id.apk_logo)
        ImageView mApkLogo;
        @InjectView(R.id.tv_apk_name)
        TextView mTvApkName;
        @InjectView(R.id.tv_apk_info)
        TextView mTvApkInfo;
        @InjectView(R.id.tv_download_times)
        TextView mTvApkDownloadTimes;
        @InjectView(R.id.tv_apk_score)
        TextView mTvApkScore;
        @InjectView(R.id.tv_apk_coin)
        TextView mTvApkCoin;
        @InjectView(R.id.download_button)
        Button mBtnDownload;
        @InjectView(R.id.download_progress)
        ProgressBar mPgDownload;

        public ViewHolder(View view) {
            ButterKnife.inject(this, view);
        }
    }
    
    public static final AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
            try {
				String msg = new String(arg2,"utf-8");
				AppContext.showToast(msg);
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			// 处理成功后的动作
			try {
				Thread.sleep(180000);
				String result = new String(arg2,"utf-8");
				JSONObject jObj = new JSONObject(result);
				if (jObj.getString("result").equals("success")) {
					AppContext.showToast("恭喜你，获取了"+jObj.getString("score")+"分");;
				}
			} catch (Exception e) {
				e.printStackTrace();
                onFailure(arg0, arg1, arg2, e);
			}
		}
    };
	
}

